package cas;

/**
 * 描述：两个线程竞争一个变量
 */

public class TwoThreadCompetiton {
    private volatile int value;

    public synchronized int compareAndSwap(int expectedValue, int newValue) {
        int oldValue = value;
        if (oldValue == expectedValue) {
            value = newValue;
        }
        return oldValue;
    }

    public static void main(String[] args) {
        TwoThreadCompetiton cas = new TwoThreadCompetiton();
        cas.value = 0;
        Thread t1 = new Thread(() -> cas.compareAndSwap(0,1), "t1");
        Thread t2 = new Thread(() -> cas.compareAndSwap(0,2), "t2");
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(cas.value);
    }
}
